var play = play||{};

play.init = function (my){
	play.my=my;
	play.isPlay=false ;

	if(my==1){
		let dices = [];
		for(let i=0;i<6;++i){
			dices[i]=Math.floor(Math.random()*6+1);
		}
		let turn=1;
		if(Math.random() < 0.5)
			turn=-1;
		net.send(JSON.stringify({_:"initDice",dices:dices,turn:turn}));
	}

}

play.initDice = function(dices,turn){
	play.dices = dices;
	play.isPlay=true ;
	play.selfReady=false;
	play.targetReady=false;
	play.n=0;
	play.m=0;
	play.turn = turn;
	if(play.my==1)
		com.get("myPoint").innerText=dices[0]+", "+dices[1]+", "+dices[2];
	else
		com.get("myPoint").innerText=dices[3]+", "+dices[4]+", "+dices[5];
	com.get("selN").value="1";
	com.get("selM").value="1";
	com.log("对局开始，" + (play.my==play.turn?"你先选择":"对方选择"));
}

com.get("believe").onclick=()=>{
	if (!play.isPlay || play.my != play.turn) return;
	if(play.n>=6 && play.m>=6){
		alert("对方叫数已经到了极限，只能选择不信");
		return;
	}
	let n=com.get("selN").value;
	let m=com.get("selM").value;
	if(n < play.n){
		alert("叫数的数量不能比" + play.n + "小");
		return;
	}
	if(n == play.n && m <= play.m){
		alert("叫数的数量相同时，点数必须比" + play.m + "大");
		return;
	}
	net.send(JSON.stringify({_:"believe",n:n,m:m}));
};

play.believe = function(n,m){
	play.n=n;
	play.m=m;
	com.log((play.turn==play.my?"你：":"对方：")+n+"个"+m);
	play.turn = -play.turn;
}

com.get("disbelieve").onclick=()=>{
	if (!play.isPlay || play.my != play.turn || play.n==0) return;
	net.send(JSON.stringify({_:"disbelieve"}));
};

play.disbelieve = function(){
	com.log((play.turn==play.my?"你不信":"对方不信"));
	com.log("对方点数："+(play.my==1?(play.dices[3]+", "+play.dices[4]+", "+play.dices[5]):(play.dices[0]+", "+play.dices[1]+", "+play.dices[2])));
	let rn = 0;
	for(let i=0;i<play.dices.length;++i){
		if(play.dices[i]==play.m||play.dices[i]==1)
			++rn;
	}
	if(rn<play.n)
		play.showWin(play.turn==play.my);
	else
		play.showWin(play.turn!=play.my);
}

play.showWin = function (my){
	play.isPlay = false;
	if (my){
		com.log("恭喜你，你赢了！");
	}else{
		com.log("很遗憾，你输了！");
	}
}
